package com.verlet.springbootdemo.service;

import com.verlet.springbootdemo.entity.Temperature;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 模拟传感器定时产生数据
 *
 * @author Verlet
 * @date 2023-02-02 00:49
 */
@Component
public class TemperatureSensor {

    private final ApplicationEventPublisher publisher;

    private final Random rnd = new Random();

    private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

    public TemperatureSensor(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }

    @PostConstruct
    public void startProcessing() {
        this.scheduledExecutorService.schedule(this::probe, 1, TimeUnit.SECONDS);
    }

    private void probe() {
        double temperature = 16 + rnd.nextGaussian() * 10;
        publisher.publishEvent(new Temperature(temperature));
        scheduledExecutorService.schedule(this::probe, rnd.nextInt(5000), TimeUnit.MILLISECONDS);

    }
}
